package hn.cch.grammar.net.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by CCH on 2018/5/7.
 */
public class Client {
    public static void main(String[] args) {
        //客户端程序
        //主机和端口

        int port = 8080;
        try {
            InetAddress address = InetAddress.getByName("127.0.0.1");
            Socket client = new Socket(address, port);
            System.out.println("客户端连接");
            System.out.println(client);
            try {
                //输入
                BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                //输出
                PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

                while (true) {
                    System.out.println("输入发送内容（为空断开连接）：");
                    //控制台输入
                    Scanner scanner = new Scanner(System.in);
                    String string = scanner.nextLine();
                    writer.println(string);
                    //为空退出
                    if (string.equals("")) {
                        break;
                    }
                    //控制台输出
                    String str = reader.readLine();
                    System.out.println(str);
                }
            } finally {
                System.out.println("客户端断开");
                client.close();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

}
